package com.wutianyi.activemq.example;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;

public class EmbededBroker {

	public static void main(String[] args) {
		BrokerService broker = new BrokerService();
		try {
			broker.addConnector("tcp://localhost:61619");
			broker.setBrokerName("test");
			broker.start();

			ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
					"vm://localhost:61619");
			Connection connection = connectionFactory.createConnection();
			connection.start();
			Session session = connection.createSession(false,
					Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue("TEST");
			MessageProducer producer = session.createProducer(destination);
			producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
			producer.send(session.createTextMessage("Hello"));
			session.close();
			connection.close();

			connection = connectionFactory.createConnection();
			connection.start();
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			Destination des = session.createQueue("TEST");
			MessageConsumer consumer = session.createConsumer(des);
			Message message = consumer.receive(1000);
			if (message instanceof TextMessage) {
				System.out.println(((TextMessage) message).getText());
			}
			session.close();
			connection.close();
			broker.stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
